// miniprogram/pages/SupportPage/questions/questions.js
const util = require("../../../utils/util");
const db = wx.cloud.database()
const dbCmd = db.command;

let superArgs = ""; //存放来自上级页面传入的参数
let quesTitle = ""; //存放问卷标题
let quesName = ""; //存放问卷的集合名称, 比如"ques-onlineDating"
let id = 0; //存放问卷的id
let quesDetailVar = ""; //存放问卷内容
let userInfoQuestions_2 = ""; //存放问卷页面所获取的用户信息缓存, 并保存与当前页面的变量中
let loginStatus = false; //用户登录状态
let pageExit = false; //若为true, 则退出当前页面
let ansSet = new Set(); //用于存放用户回答的题目

function setUserInfo(option) {
    userInfoQuestions_2 = option.data.event.userInfo;
    loginStatus = true;
}

// function popUpExit(that) {
//     // that 是保存修改数据的指针
//     if (pageExit) {
//         wx.navigateBack({
//             delta: 1,
//             complete(complete) {
//                 that.setData({complete})
//                 console.log("complete wx.navigateBack")
//             }
//
//         });
//     } else {
//         console.log("pageExit: else");
//         that.setData({
//             popUpShow: false
//         });
//     }
// }

Page({
    data: {
        quesDetail: "", //存放传入页面的问卷内容
        title: "", //问卷标题
        loginStatus: false,
        userInfoQuestions: "", //存放问卷页面所获取的用户信息缓存
        changed: {}, //存放用户作答的键值对
        popUpShow: false,
        duration: 300,
        popUpMsg: '', //弹窗的提示语句
        pageExit: false, //若为true, 则退出当前页面
    },
    onLoad: function (options) {

        let that = this; //暂时保存this指针, 后面在success回调函数中使用
        wx.getStorage({
            key: "userInfo_2",
            success(res) {
                that.setData({
                    userInfoQuestions: res.data.event.userInfo
                });
                setUserInfo(res);
            }
        });
        superArgs = Object.values(options);
        quesName = superArgs[1];
        quesTitle = superArgs[2];
        this.getData();
    },
    getData() { //从后台获取问卷目录
        db.collection(quesName).get().then(res => {
            quesDetailVar = res.data;
            this.setData({
                quesDetail: quesDetailVar,
                title: quesTitle
            });
        })
        this.initQuestionPage(); // 用户问卷的回答统计变量初始化
    },
    closeQuestion(e) {
        if (ansSet.size !== Object.keys(this.data.quesDetail).length) {
            //如果没有回答全部的问题就无法交卷
            let msg = "还没有完成问卷喔~ ";
            this.setData({
                popUpMsg: msg
            })
            this.popup(e);
        } else {
            let that = this;
            let userAnsCol = [{
                quesName: quesName,
                quesTitle: quesTitle,
                answer: that.data.changed,
                time: util.formatTime(new Date())
            }];//存放用户所回答的问卷名称、所回答的答案以及时间

            db.collection('userAnswers')
                .where({
                    _openId: userInfoQuestions_2.openId
                }).get().then(res => {
                //res包含查询到的结果
                if (res.data.length === 0) {
                    console.log("temp为空")
                    //未找到此openId, 便写入新的值
                    db.collection('userAnswers').add({
                        data: {
                            userAnsCol: userAnsCol
                        }
                    });
                } else {
                    //先找到用户, 再检查用户有没有填写过相同的问卷, 若有, 则覆盖; 反之新增
                    db.collection('userAnswers')
                        .where({
                            _openid: userInfoQuestions_2.openId
                        }).get().then(res => {
                        for (var i = 0, len = res.data["0"].userAnsCol.length; i < len; i++) {
                            if (res.data["0"].userAnsCol[i] === quesTitle) {

                            }
                        }
                    });
                    db.collection('userAnswers')
                        .where({
                            _openid: userInfoQuestions_2.openId
                        }).update({
                        data: {
                            userAnsCol: dbCmd.push(userAnsCol)
                        }
                    });
                }
            })
            let msg = "感谢填写问卷~";
            pageExit = true;
            this.setData({
                popUpMsg: msg
            })
            this.popup(e);
        }

    },
    initQuestionPage() {
        for (var i = 0; i < this.data.quesDetail.length; i++) {
            this.data.changed[i] = ''; //把所有问题的回答全部置为空, 以实现初始化回答的目的
        }
        this.setData(this.data.changed);
    },
    radioChange: function radioChange(foeld, event) {
        var selectedAsk = foeld.target.dataset.ask; //被选中的问题
        var answer = foeld.detail.value; //用户的回答

        this.data.changed[selectedAsk] = answer;
        ansSet.add(selectedAsk);
        this.setData(this.data.changed);
        this.setData(ansSet);
    },
    popup(e) {
        let duration = this.data.duration;
        this.setData({
            popUpShow: true,
            duration
        })
    }, popUpExit() {
        let that = this;
        // this.setData({pageExit: pageExit})
        pageExit = this.data.pageExit;
        if (pageExit) {
            wx.navigateBack({
                delta: 1,
                success(success) {
                    that.setData({success})
                    console.log("success: " + success.errMsg);
                }, fail(fail) {
                    that.setData({fail})
                    console.log("fail: " + fail.errMsg);
                }, complete(complete) {
                    that.setData({complete})
                    console.log("complete: " + complete.errMsg)
                }

            });
        } else {
            console.log("pageExit: else");
            that.setData({
                popUpShow: false
            });
        }
    },
})